import express from 'express';
import Ret, { RetCode } from '../../bean/code/Ret';
const app = express();
import { Op } from 'Sequelize'
import { db, Sequelize } from '../../dao/config';
import { converPage } from '../../bean/page';
import { excludeEmpty } from '../../utils';
import logger from '../../utils/logger';
const Product = require("../../dao/models/f_product")(db, Sequelize);

/**
 * 查詢所有商品
 */
app.post("/product/getAllProductByCondition", async (req, res) => {
    let params = req.body, { page = {} } = params, { pageSize = 10, pageNum = 1 } = page;
    const condition = excludeEmpty(params, Product);
    if (params.priceRange) {
        condition.price = { [Op.between]: params.priceRange }
    }
    if (params.createTimeRange) {
        condition.createTime = { [Op.between]: params.createTimeRange }
    }
    try {
        const products = await Product.findAndCount({ 
            where: condition, order: [
                ['createTime', 'DESC'],
            ], ...converPage(pageSize, pageNum)
        });
        res.json(Ret(RetCode.SUCCESS).setData(products));
    } catch (e) {
        res.status(500).json(e);
    }
})
/**
 * 下架指定一些商品
 */
app.post("/product/invalidProducts", async (req, res) => {
    const { ids, invalid } = req.body;
    const updateRes = await Product.update({ invalid }, { where: { id: ids } });
    res.json(Ret(RetCode.SUCCESS).setData(updateRes));
});
/**
 * 删除指定一些商品记录
 */
app.post("/product/deleteProducts", async (req, res) => {
    const { ids } = req.body;
    const deleteRes = await Product.destroy({ where: { id: ids } });
    res.json(Ret(RetCode.SUCCESS).setData(deleteRes));
});/**
 * 恢复失效商品
 */
app.post("/product/restoreProducts", async (req, res) => {
    const { id, invalid } = req.body;
    const updateRes = await Product.update({ invalid }, { where: { id } });
    res.json(Ret(RetCode.SUCCESS).setData(updateRes));
});
/**
 * 获取所有商品
 */
app.get("/product/getAllProductIdsAndName", async (req, res) => {
    const products = await Product.findAll({
        attributes: ["name", "id"],
        order: [
            ['createTime', 'DESC'],
        ]
    });
    res.json(Ret(RetCode.SUCCESS).setData(products));
})
/**
 * 获取单个商品
 */
app.get("/product/getProductById", async (req, res) => {
    const product = await Product.findById(req.query.id);
    res.json(Ret(RetCode.SUCCESS).setData(product));
})
/**
 * 修改单个商品
 */
app.post("/product/updateProduct", async (req, res) => {
    const condition = req.body, { id } = condition;
    const updateRes = await Product.update(excludeEmpty(condition, Product), { where: { id } });
    res.json(Ret(RetCode.SUCCESS).setData(updateRes));
})
/**
 * 增加单个商品
 */
app.post("/product/addProduct", async (req, res) => {
    const condition = req.body, { id } = condition;
    const insertRes = await Product.create({ ...excludeEmpty(condition, Product), createTime: new Date() });
    res.json(Ret(RetCode.SUCCESS).setData(insertRes));
})


export default app;
